<template>
    <div class="tableRow fullscreen-container" ref="surveyDiv" height="100vh">
        <div class="tableRow" >
            <invest-table-manual ref="investTableManualCommon" v-if="tabItem && tabItem.gridCategory==='common'" :operate-options="operateOptions" @invest-table-operate-click="handleOperateClick"
                                 :models="models.common" :tableHeight="tableHeight" :formData="formData.commonForm" :validateData="validateData"/>

    </div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Ref, Prop } from 'vue-property-decorator';
import { getStructureById } from '@/api/investStructure';
import { surveyByStructureId } from '@/api/investSubStructure';
import DynamicModel from '@/components/DynamicModel.vue';
import InvestTableManual from '@/components/verify/InvestTableManual.vue';
import FileUploadComp from '@/components/FileUploadComp.vue';
import { addFromOnline ,historyList,prepareNotChange} from '@/api/investDataCommon';
import NTab from "@/components/NTab.vue";
import VueFullscreen from 'vue-fullscreen'; 
import {removeEvidence} from '@/api/investDataCommon';
import {validateData} from '@/api/inspectTask';

import DataTable from '@/components/DataTable/DataTable.vue';
@Component({ components: { DynamicModel,VueFullscreen ,InvestTableManual,NTab,FileUploadComp,DataTable} })
export default class SurveyModelManual extends Vue {

    @Ref("investTable") investTable!: any;
    @Ref("dataTable") dataTable!: any;
    @Ref("surveyDiv") surveyDiv!:any;
    @Ref("dynamicDataTable") dynamicDataTable!:any;
    @Ref("investTableManualCommon") investTableManualCommon!:any;
    @Prop() private operateOptions:any;
    @Prop() private structureId!: any;
    @Prop({
        default: () => 290
    }) private tableHeight!:any;
    @Prop({
        default: () => false
    }) 
    private isEdit;
    @Prop({
        default: () => false
    }) 
    private showHistory;
    validateData:any ={};
    historyApi = historyList;
    fileList=[];
    tableTab='first';
    tabOptions:any=[{label:'基本附表',gridCategory:'common'}]
    tabItem:any = this.tabOptions[0];
    fileUploadOption:any={
        url:'/bus/data/importEvidence',
        uploadTip:'请选择文件',
        fileList:[],
        removeApi: removeEvidence,
    }
    formData:any ={
        commonForm:{},
        commonExtForm:{},
        dynamicForm:{}
    };
    models:any = {//分页参数
        structure: {
            title: '',
            subTitle: '',
            monthId: '',
            id: '',
            categoryId: '',
        },
        common: {
            id: '',
            title: '',
            headCode: [],
            endCode: [],
            data: [],
            evidence:'',
            region:{},
        },
        dataCodeType: [],
        dataCodeTypeExt:[],
        selectDeptId: '',
        surveyInfo: [],
        commonExt: {
            id: '',
            title: '',
            headCode: [],
            endCode: [],
            data: []
        },
        dynamic: {
            id: '',
            title: '',
            headCode: [],
            endCode: [],
            dynamicTitle: [],
            dynamicDefineData: [],
            dynamicDataList: [],
            lastDataList: [],
        },
        activities: []
    };

    
    fullscreen = false;

    tableOptions: any = {
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        multipleSelect: true, // 是否支持列表项选中功能
    };

    selectFormModel:any={
        departId:''
    };
    columns: any = [
  {
      label: 'ID',
      prop: 'id',
      hide: true
    },
    {
      label: '调查任务',
      prop: 'workName',
    },
    {
      label: '调查结构',
      prop: 'structureName'
    },
    {label: '创建时间', prop: 'createTime', sortable: 'custom', width: 160, showOverflowTooltip: true},
   
  ];
  operates: any = {
    width: 200,
    fixed: 'right',
    list: [
      {
        label: '比对',
        type: 'warning',
        icon: 'el-icon-edit',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:data:list',
        method: (index, row) => {
          this.handleCompare(index, row);
        }
      },
    ]};

    options: any = {
        searchTitle: '普查数据',
        commonData: {},
        codeNumbers: ['01', '02', '03', '04', '05', '06'],
        selectParams: {
            placeholder: '请选择'
        },
        treeParams: {
            clickParent: true,
            filterable: true,
            accordion: true,
            data: [],
            props: {
                children: 'children',
                label: 'label',
                disabled: 'disabled',
                value: 'id'
            }
        }
    }

  //操作列触发事件
  handleOperateClick(row) {
    this.$emit('invest-table-operate-click', row);
  }

    successHandler(){
        console.log("11")
    }

    handleCompare(index, row){
        const queryData = {dataId: this.formData.commonForm.id,structureId:this.structureId,
            historyDataId: row.id, historyStructureId: row.structureId
        }
        this.$router.push({ path: '/quality/compareView', query: queryData});
        console.log("dfd")
    }


    handleSelectionChange(val): void {
        console.log("选择" +val);
    }
    copyFromData(form:any, toForm:any, model:any){
     
        toForm.id = form.id;
        if(form && form.head ){
            Object.assign(toForm.head, form.head);
        }
        if(form && form.end){
            Object.assign(toForm.end, form.end);
        }
       
        if(form.code && model){
            Object.keys(model.checkCodeType).forEach(k =>{
            const dt = form.code[k];
            if(dt){
               const ct = model.checkCodeType[k];
               switch(ct){
                case '0':
                    toForm.code[k] = dt
                    break;
                case '1':
                   
                    if(dt.includes(';')){
                        const spdt =  dt.split(';');
                        toForm.code[k] = [spdt[0]];
                        toForm.codeExt[k] = [spdt[1]];
                    }else{
                        toForm.code[k] = [dt];
                    }
                    break;
                case '2':
                    if(dt.includes(';')){
                        const spdt:any =  dt.split(';');
                        if(spdt.some(s => s.includes('其他') || s.includes('其它'))){
                            toForm.code[k]  = spdt.slice(0, -1);
                            toForm.codeExt[k] = spdt[spdt.length - 1];
                        }else{
                            toForm.code[k] = spdt;
                        }
 
                    }else{
                        toForm.code[k] = [dt];
                    }
                    break;
               }
            }
        })
        }
       
    }

    
  tabCheckHandler(data){
    this.tabItem = {...data.item};
  }
    
    addFormData(data:any){
        this.fileUploadOption.fileList=[];
        this.$nextTick(() =>{
            setTimeout(() =>{
                if(data.commonForm){
                    this.fileUploadOption.fileList = data.commonForm.evidenceList;
                    this.copyFromData(data.commonForm,this.formData.commonForm,this.models.common);
                    if(data.commonForm.departId && this.showHistory){
                        this.selectFormModel.departId = data.commonForm.departId;
                        if(this.dataTable){
                            this.dataTable.refreshData(this.historyApi);
                        }
                      
                    }
                }
                if(data.commonExtForm){
                    this.copyFromData(data.commonExtForm,this.formData.commonExtForm,this.models.commonExt);
                }
            
                if(data.dynamicForm){
                    Object.assign(this.formData.dynamicForm.head,data.dynamicForm.head);
                    Object.assign(this.formData.dynamicForm.end,data.dynamicForm.end );
                    this.dynamicDataTable.addDynamicDataList(data.dynamicDataList);
                
                }
            },1500);
            
        })
    }

    findStructure() {
        getStructureById({ id: this.structureId }).then(res => {
            if (res.data) {
                this.models.structure.title = res.data && res.data.title;
                this.models.structure.subTitle = res.data && res.data.subTitle;
                this.models.structure.monthId = res.data && res.data.monthId + '';
                this.models.structure.categoryId = res.data && res.data.categoryId + '';
                this.models.structure.id = this.structureId;
            }
        }).catch(e => {
            console.error(e);
        });
    }

      async surveyInfo() {
        await surveyByStructureId({ id: this.structureId }).then(res => {
            if (res.data) {
                this.models.surveyInfo = res.data;
                 this.extractSuerveyData();
            }
        }).catch(e => {
            console.error(e);
        });
    }

    updateHeadCode(code:any, val:any){
        if(code in this.formData.commonForm.head){
            this.formData.commonForm.head[code] =val;
        }
        if(this.formData.commonExtForm && this.formData.commonExtForm.head && code in this.formData.commonExtForm.head){
            this.formData.commonExtForm.head[code] =val;
        }
        if(this.formData.dynamicForm && this.formData.dynamicForm.head && code in this.formData.dynamicForm.head){
            this.formData.dynamicForm.head[code] =val;
        }
    }

    updateCode(code:any, val:any){
        if(code in this.formData.commonForm.code){
            this.formData.commonForm.code[code] =val;
        }
    }

    async extractSuerveyData() {
        
        if (this.models.surveyInfo && this.models.surveyInfo.length > 0) {
            this.models.dynamic.id = '';
            this.models.common.id = '';
            this.models.commonExt.id = '';
            this.models.surveyInfo.forEach((si:any) =>{
               
                switch(si.gridCategory){
                    case 'common':
                        this.formData.commonForm = {...si.formData};
                        this.models.common = si;
                        this.fileUploadOption.id = this.models.common.id;
                        break;
                        
                    case 'commonExt':
                        this.formData.commonExtForm = {...si.formData};
                        this.models.commonExt = si;
                        this.tabOptions.push({label:'扩展附表', gridCategory:'commonExt'})
                        break; 
                    case 'dynamic':
                        this.models.dynamic = si;
                        this.formData.dynamicForm = si.formData;
                        this.tabOptions.push({label:'其它附表', gridCategory:'dynamic'})
                        this.models.dynamic.dynamicTitle = JSON.parse(this.models.dynamic.dynamicTitle);
                        break;

                }
            });
           
            this.tabOptions.push({label:'佐证材料', gridCategory:'evidence'})
            if(this.showHistory){
                this.tabOptions.push({label:'历史数据', gridCategory:'history'})
            }
            
        }
    }


    dynamicSubStructureHandler(val: any) {
        if (val && val.length > 0) {
            this.models.dynamic.dynamicDataList = val.map(obj => {
                const { id, ...rest } = obj;
                return rest;
            });
        }
    }

    /**
     * @author baomz
     * @param common 
     * @param form 
     */
    handlerCheckTypeCode(common:any, form:any, toForm:any, status:any){

        for (let key in common.checkCodeType) {

            let dt = form.code[key];
            
            if(!dt){
                continue;
                // if(status==='0'){
                //         continue;
                //     }
                // this.$message(`${common.checkCodeName[key]} 为空`);
                // return false;
            }
            let contentType = common.checkCodeType[key];
            if (contentType === '1' ) {
                if(dt.length == 0){
                    continue;
                    // this.$message(`${common.checkCodeName[key]} 为空`);
                    // return false;
                }
               
                let extDt = form.codeExt[key];
                toForm.code[key] = dt[0] + '';
                if(extDt){
                    toForm.code[key] +=';' + extDt;
                }
                
            }else if(contentType === '2'){
                if(dt.length == 0){
                   continue;
                    // this.$message(`${common.checkCodeName[key]} 为空`);
                    // return false;
                }
                let extDt = form.codeExt[key];
               
                if(dt.length > 1){
                    toForm.code[key] = dt.join(';');
                }else{
                    toForm.code[key] = dt[0] + '';
                }
                if(extDt){
                    toForm.code[key] += ';' + extDt;
                }
            }else{
                toForm.code[key] = dt;
            }
        }
        return true;
    }




    handleSubmit(formData:any,status:any) {
        this.$confirm('确定要提交调查数据码？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            const copyForm:any = {commonForm:{head:{},end:{},code:{}},commonExtForm:{head:{},end:{},code:{}},dynamicForm:{head:{},end:{},code:{}}};
            let notChange:any = false;
            if(formData.changeStatus && status =='1'){
                copyForm.commonForm.changeStatus= formData.changeStatus;
                if(formData.changeStatus =='1'){
                   prepareNotChange({id:this.formData.commonForm.id}).then(res =>{
                        (this as any).$bus.$emit('refreshData');
                        this.$message.info("数据已核实不变");
                   }).catch(e =>{
                        console.log(e);
                   })
                   return;
                }
            }


            if(!formData.areaId){
                this.$message.error("请选择区划");
                return;
            }

            copyForm.commonForm.workId = formData.workId;
            copyForm.commonForm.areaId = formData.areaId;
            copyForm.commonForm.departId = formData.departId;
            copyForm.commonForm.vectorId = formData.vectorId;
            copyForm.commonForm.polygon = formData.polygon;
            copyForm.commonForm.status = formData.status;
            copyForm.commonForm.point = formData.point;
          
          
            

            if(this.models.common.id ){
                if(!notChange){
                    this.handlerCheckTypeCode(this.models.common,this.formData.commonForm, copyForm.commonForm,status);
              
                }
               
                copyForm.commonForm.categoryId = this.models.structure.categoryId;
                copyForm.commonForm.id = this.formData.commonForm.id;
                copyForm.commonForm.structureId = this.models.structure.id;
                copyForm.commonForm.categoryId = this.models.structure.categoryId;
                copyForm.commonForm.title = this.models.structure.title;
                copyForm.commonForm.subTitle = this.models.structure.subTitle;
                copyForm.commonForm.subStructureId = this.models.common.id;
              
                    copyForm.commonForm.head = {...this.formData.commonForm.head};
                    copyForm.commonForm.end = {...this.formData.commonForm.end};
               
               
                if(this.fileUploadOption.fileList && this.fileUploadOption.fileList.length > 0){
                    copyForm.commonForm['hasEvidence'] = true;
                }
            }
           
          
           if(this.models.commonExt.id){
               
                    this.handlerCheckTypeCode(this.models.commonExt,this.formData.commonExtForm,copyForm.commonExtForm,status);
                    copyForm.commonExtForm.head = {...this.formData.commonExtForm.head};
                    copyForm.commonExtForm.end = {...this.formData.commonExtForm.end};
                
                copyForm.commonExtForm.id = this.formData.commonExtForm.id;
                copyForm.commonExtForm.subStructureId =  this.models.commonExt.id
                copyForm.commonExtForm.structureId =  this.models.structure.id;
                copyForm.commonExtForm.title = this.models.structure.title;
                copyForm.commonExtForm.subTitle = this.models.structure.subTitle;
           }
         

            //动态表单收集数据
            if (this.models.dynamic && this.models.dynamic.id && this.models.dynamic.dynamicDataList && this.models.dynamic.dynamicDataList.length > 0 &&!notChange) {
        
                copyForm.dynamicList = [];
                this.models.dynamic.dynamicDataList.forEach((dynamicData: any) => {
                    const obj={code:{},head:{},end:{},structureId:this.models.structure.id,subStructureId: this.models.dynamic.id};
                    obj.code = dynamicData;
                    obj.head = this.models.formData.dynamicForm.head;
                    obj.end = this.models.formData.dynamicForm.end;
               
                    copyForm.dynamicList.push(obj);
                
                })
            }
            if(!notChange){
                validateData(copyForm).then(res =>{
                if(res && res.data && res.data.length > 0){
                    res.data.forEach(dt =>{
                        this.$set(this.validateData, "code" +dt.subFieldCode, dt.remark);
                    });
                    if(status === '0') {
                         addFromOnline(copyForm).then((res: any) => {
                            if(res && res.data){
                              
                                if(res.code=== 500){
                                this.$message.error(res.msg);
                                }
                                if(res.code === 200){
                                    this.$message.success(res.msg);
                                    this.formData.commonForm.id = res.data;
                                
                                }
                              
                            }
                        
                        });
                    }else{
                        this.$message.error("数据校验失败不能提交，请点击保存");
                    }

                }else{
                     addFromOnline(copyForm).then((res: any) => {
                            if(res && res.data){
                                if(res.code=== 500){
                                this.$message.error(res.msg);
                                }
                                if(res.code === 200){
                                    this.$message.success(res.msg);
                                    this.formData.commonForm.id = res.data;
                                }
                            }
                        
                        });
                }
            }).catch(e=>{
                this.$message.error("校验数据失败");
            })
            }
         
           
        }).catch((e) => {
            console.error(e);
        });
    }

    async refreshModel(){
        
        if(this.structureId){
           await this.findStructure();
            this.surveyInfo();
        }
    }

    created() {
    
        this.refreshModel();
    }

    toggleFullScreen() {
      this.fullscreen = !this.fullscreen;
      if (this.fullscreen) {
        this.tableHeight='60vh'
        this.surveyDiv.requestFullscreen();
        // 临时禁用背景色样式测试
        document.body.style.backgroundColor = 'transparent'; // 或者其他颜色测试
      } else {
        this.tableHeight='50vh'
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
        // 恢复背景色样式测试
        document.body.style.backgroundColor = ''; // 恢复默认或指定颜色
      }
    }

    handleBeforeUnload(event) {
        // 在这里编写你想要执行的代码
        // 例如：提示用户是否真的想要关闭页面
        event.preventDefault();
        event.returnValue = '';
    }

    back2DataHandler(){
        this.$destroy();
        this.$router.go(-1);
    }

    beforeDestroy() {
        // 组件销毁前移除事件监听
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
    }
    mounted(){
        document.addEventListener('fullscreenchange', () => {
        if (document.fullscreenElement) {
            // 全屏时执行的代码，如清除默认样式等
            document.documentElement.style.backgroundColor = '#000'; // 或其他颜色测试
        } else {
            // 非全屏时恢复的代码
            document.documentElement.style.backgroundColor = ''; // 恢复默认颜色或其他样式设置
        }
        });

    }
}
</script>

<style scoped>
::v-deep .textCenter {

    text-align: center;
   
}
::v-deep .select-list{
    background-color:#fff;
}

::v-deep .headerTitle {
    margin-left: 0px;
    margin-bottom: 0px;
}

::v-deep .bg-purple-dark {
    background: #99a9bf;
}

::v-deep .bg-purple {
    background: #d3dce6;
}

::v-deep .bg-purple-light {
    background: #f8f9fc;
}

::v-deep .grid-content {
    border-radius: 4px;
    min-height: 36px;
}

::v-deep .inputLabel {
    color: #000;
    background-color: #fff;
    padding: 0;
    margin: 0;

}

::v-deep .tableRow {
    padding: 0px;
    margin: 0px;
  background: #ffffff;
}

::v-deep .tableRow .el-row {
    width: 100%;
    height: 100%;
}

::v-deep .el-input-group__prepend {
    background-color: #fff;
    border: 0;
}

::v-deep .el-input-group__prepend {
    border: 0;
    background-color: #fff;
}

::v-deep .el-input__inner {
    border: 0;
    background-color: #fff;
}

::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner {
    background-color: #FFf;
    border-color: #000;
    cursor: not-allowed;
}

::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    /* background-color: #fff; */
    border-color: #000;
}

::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
    border-color: #000;
}

::v-deep .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    border-color: #000;
    color: #000;
    cursor: not-allowed;
}

::v-deep .el-checkbox__input.is-disabled+span.el-checkbox__label {
    color: #000;
    cursor: not-allowed;
}


::v-deep .el-card__body {
    margin: 0px;
    padding: 0px;
}
::v-deep .my-component {
  pointer-events: none; /* 让这个组件不接收鼠标事件 */
}
::v-deep .fullscreen-container {
  z-index: 999;
  min-height: 100vh;
 /* 或更高的值 */
}
::v-deep .toggle-button{
    z-index:2000;
    float: right;
    position: absolute;
    right:0px;
    background-color:#fff;
    border:0px;
}

::v-deep .back-button{
    z-index:2000;
    float: right;
    position: absolute;
    right:40px;
    background-color:#fff;
    border:0px;
}
</style>